import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'

// Custom APIs for renderer
const api = {
  // 渲染进程向主进程通信
  apiIsLogin: (data) => {
    ipcRenderer.send('is-login', data)
  },
  apiDragRender: (data) => {
    ipcRenderer.send('drag-render', data)
  },
  apiToggleFullScreen: (data) => {
    console.log('进入到preload')
    console.log('ipcRenderer', ipcRenderer)
    try {
      //   ipcRenderer.send('toggle-full-screen', data)
      ipcRenderer.send('toggleFullScreen', data)
    } catch (error) {
      console.log(error, 'error')
    }
    // return ipcRenderer.invoke('toggle-full-screen', data)
  },
  apiWindowMinimize: (data = true) => {
    ipcRenderer.send('window-minimize', data)
  },
  apiWindowClose: (data = true) => {
    ipcRenderer.send('window-close', data)
  },
  apiClickMenu: (data) => {
    ipcRenderer.send('click-menu', data)
  },
  apiCreateNestWindow: (data) => {
    ipcRenderer.send('create-nest-window', data)
  },
  apiIsMainWindow: (data) => {
    ipcRenderer.send('is-main-window', data)
  },
  // 主进程向渲染进程通信
  apiSwitchToFile: (callback) => ipcRenderer.on('switchToFile', (event, data) => callback(data)),
  apiOpenFileMes: (callback) => ipcRenderer.on('openFileMes', (event, data) => callback(data)),
  apiSendError: (callback) => ipcRenderer.on('sendError', (event, data) => callback(data))
}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  window.electron = electronAPI
  window.api = api
}
